var Session = require('../../vendor/qcloud-weapp-client-sdk/lib/session.js');
var config = require('../../config.js');
var commons = require('../../commons.js');
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');
var register = require('../../template/register/register.js');
var utils = require('../../vendor/qcloud-weapp-client-sdk/lib/utils.js');
var WxParse = require('../wxParse/wxParse.js');
var JlnumS = 0;
var aQp = 0; //定义一个全局变量
var bXz = 0; //定义一个全局变量
var tsay = 0; //判断说话太快了
const Flutter = require('./flutter-hearts-zmt.js');
let bgImg = '';
let headerImg = '';
let random = {
  uniform: function(min, max) {
    return min + (max - min) * Math.random();
  },
  uniformDiscrete: function(i, j) {
    return i + Math.floor((j - i + 1) * random.uniform(0, 1));
  },
};
let imgs = [{
    url: 'img/1.png',
    width: 30,
    height: 30
  },
  {
    url: 'img/2.png',
    width: 30,
    height: 30
  },
  {
    url: 'img/3.png',
    width: 30,
    height: 30
  },
  {
    url: 'img/4.png',
    width: 30,
    height: 30
  },
  {
    url: 'img/5.png',
    width: 30,
    height: 30
  }
]
var index = {

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    tabList: ["互动", "榜单", "介绍"],
    ia: "", //接收传过来的直播间id
    detailData: "", //房间的数据
    scrollTop: 0, //判断输入框的位置
    pullbg: false, //判断视频封面图
    HtmlUrlData: "", //浏览器网页地址
    beginHide: false, //判断开始直播按钮是不是有
    // 发送实时聊天
    access_token: '',
    nickname: '',
    avatar_url: '',
    liaoTianid: '',
    canvasShow: false, //二维码分享海报图
    wxHeight: "", //获取小程序的高度
    playBegin: false, //开始播放视频
    userId: '',
    imgal: "",
    newsList: [], //追加聊天信息
    oldNewList: "", //历史聊天记录
    guanzhuShow: true,
    isOpenData: 0,
    dataTimeHtml: '距开始还有:00天00小时00分00秒', //倒计时时间
    timeShow: false, //倒计时显示判断
    time: 15, //
    input: '', //聊天框内容
    wxW: '750rpx',
    orientation: "vertical",
    wxH: '225px',
    // 点赞量
    zanNumData: '1',
    zanNumtext: '0',
    // 观看量
    countNum: "0"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var HtmlUrl = config.service.HtmlUrl + "?id=" + this.data.ia;
    console.log("浏览器网址:" + HtmlUrl);
    this.setData({
      HtmlUrlData: HtmlUrl,
      ia: options.ia,
    })
    this.flutter = new Flutter({
      width: 170,
      height: 300
    }, 'canvas');
  },
  // 回到首页
  goindex() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  //点击保存图片
  clickBcCanvasImg() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '保存海报分享到朋友圈',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: function(res) {
              console.log(res);
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(result) {
                  wx.showToast({
                    title: '图片保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            }
          })
          that.setData({
            canvasShow: false
          })
        } else if (res.cancel) {
          that.setData({
            canvasShow: false
          })
        }
      },
      fail() {
        that.setData({
          canvasShow: false
        })
        utils.showError('保存失败')
      }
    })
  },
  // 选择分享
  // 生成二维码
  clickXz() {
    var that = this;
    var textSpli = that.data.detailData.info.title;
    const ctx = wx.createCanvasContext('myCanvas');
    qcloud.request({
      login: true,
      url: config.service.myqrcodeUrl,
      data: {
        url: "../details/details?ia=" + that.data.ia
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        wx.downloadFile({
          url: res.data.data,
          success(imgbc) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            ctx.fillRect(5, 0, 320, 520)
            ctx.drawImage("../../images/fxbg.jpg", 0, 0, 320, 520)
            ctx.drawImage(headerImg, 20, 35, 40, 40)
            ctx.drawImage(bgImg, 25, 90, 270, 170)
            ctx.drawImage(imgbc.tempFilePath, 25, 400, 70, 70)

            ctx.setFillStyle('#ffffff')
            ctx.setFontSize(18)
            ctx.fillText(that.data.nickname, 197, 50)

            ctx.setFillStyle('#000')
            ctx.setTextAlign('center')
            ctx.setFontSize(20)
            if (textSpli.length > 15) {
              var textSpliAA = textSpli.slice(0, 15);
              var textSpliBB = textSpli.slice(15, 30);
              ctx.fillText(textSpliAA, 155, 300)
              ctx.fillText(textSpliBB, 155, 325)
            } else {
              ctx.fillText(textSpli, 155, 300)
            }
            ctx.draw()
            // 显示canvas画图
            that.setData({
              canvasShow: true
            })
          },
          fail(res) {
            utils.showError(res)
          }
        })
        // res是二进制流，后台获取后，直接保存为图片，然后将图片返回给前台
        // 后台二进制怎么转图片？我也不会后台，学会了再贴代码
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
        setTimeout(function() {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        }, 500)
      }
    });
  },
  // 点赞
  shoot() {
    let img = imgs[random.uniformDiscrete(0, imgs.length - 1)];
    this.flutter.bubble(img);
    this.clickzan();
  },
  clickzan() {
    var that = this;
    // 点赞请求
    wx.request({
      // 获取token
      url: config.service.clickzanUrl,
      data: {
        nums: that.data.zanNumData,
        id: that.data.ia,
      },
      success(res) {
        var zanData = "" + res.data.data.data;
        if (zanData.length >= 5) {
          that.setData({
            zanNumtext: Math.floor((zanData / 10000) * 100) / 100 + "万"
          })
        } else {
          that.setData({
            zanNumtext: zanData
          })
        }

      }
    })
  },
  // 暂时舍弃了
  // 点击全屏播放
  clickQuanPing: function() {
    if (aQp == 0) {
      aQp = 1;
      var wxH = wx.getSystemInfoSync().windowHeight;
      var wxW = wx.getSystemInfoSync().windowWidth;
      this.setData({
        wxH: wxH + "px",
        // orientation: "vertical"
      })
    } else {
      aQp = 0;
      this.setData({
        wxH: '225px',
        // orientation: "horizontal"
      })
    }

  },
  //  暂时舍弃了
  // 点击旋转
  clickxuanzhuan: function() {
    if (bXz == 0) {
      bXz = 1;
      this.setData({
        orientation: "vertical"
      })
    } else {
      bXz = 0;
      this.setData({
        orientation: "horizontal"
      })
    }

  },
  // 点击开始播放
  clickPlay() {
    var that = this;
    this.ctx.play({
      success: res => {
        console.log('play success');
        that.setData({
          pullbg: true
        })
      },
      fail: res => {
        // console.log('play fail');
        utils.showError('播放失败请重试');
        that.setData({
          pullbg: false
        })
      }
    })
  },
  // 历史浏览请求
  indexListData: function() {
    var that = this;
    qcloud.request({
      login: true,
      url: config.service.historyAddUrl,
      data: {
        room_id: this.data.ia
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {

      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {

      }
    });

  },
  // 历史聊天记录请求
  roomcommonUrl: function() {
    var that = this;
    qcloud.request({
      login: true,
      url: config.service.roomcommonUrl,
      data: {
        id: this.data.ia
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.data) {
          that.setData({
            oldNewList: res.data.data
          })
          if (that.data.isOpenData == 0){
            that.demoHeight();
          }
         
        }
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
        setTimeout(function() {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        }, 1000)
      }
    });

  },
  // 开始直播
  subAddZhiBo: function() {
    var pushurl = this.data.detailData.info.pushurl;
    var self = this;
    wx.setClipboardData({
      data: pushurl,
      success: function(res) {
        // self.setData({copyTip:true}),
        utils.showError("复制成功");
        setTimeout(function() {
          wx.navigateTo({
            url: '../push/index?pushurl=' + pushurl,
          })
        }, 500)
      }
    });

  },
  // 复制粘贴
  copyHtmlUrl: function(e) {
    var self = this;
    wx.setClipboardData({
      data: self.data.HtmlUrlData,
      success: function(res) {
        // self.setData({copyTip:true}),
        utils.showError("复制成功");
      }
    });
  },
  // 检测推流状态
  statechange(e) {
    console.log('live-player code:', e.detail.code);
    var that = this;
    if ([-2302, -2301, 3001, 3002, 3003, 3005].indexOf(+e.detail.code) !== -1) {
      setTimeout(function() {
        that.setData({
          pullbg: false,
          timeShow: true
        })
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '播放失败' + e.detail.code
        })
      }, 500)
    } else {
      console.log("开始直播:" + e.detail.code)
      that.setData({
        pullbg: true,
        timeShow: false
      })
    }
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
    setTimeout(function() {
      wx.showToast({
        image: '/res/img/err_icon.png',
        title: '播放失败'
      })
    }, 800)
  },

  // 选项卡切换
  clickTab: function(e) {
    var id = e.currentTarget.id;
    if (id == 1) {
      wx.navigateTo({
        url: '../Ranking/Ranking?detailID=' + this.data.ia,
      })
    } else {
      this.setData({
        currentTab: id
      })
    }

  },
  // 点击关注
  clickGuanZhu: function() {
    // 关注直播传的是id 不是uierid
    // type_id 0 是 直播间  type_id 1 关注是个人
    var room_id = this.data.detailData.info.id;
    var that = this;
    qcloud.request({
      login: false,
      url: config.service.collAddUrl,
      data: {
        type_id: 1,
        room_id: room_id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        utils.showError(res.data.data.msg);
        that.detailsQing();
      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {
        setTimeout(function() {
          wx.hideLoading();
          wx.stopPullDownRefresh();
        }, 500)
      }
    });
  },
  // 这个暂时舍弃了
  // 点击关注个人主播
  // clickGuanZhuZhu: function() {
  //   // 关注直播传的是id 不是uierid
  //   // type_id 0 是 直播间  type_id 1 关注是个人
  //   var room_id = this.data.detailData.info.userId;
  //   var that = this;
  //   qcloud.request({
  //     login: false,
  //     url: config.service.collAddUrl,
  //     data: {
  //       type_id: 0,
  //       room_id: room_id
  //     },
  //     header: {
  //       'content-type': 'application/json' // 默认值
  //     },
  //     success: function(res) {
  //       utils.showError(res.data.data.msg);
  //       that.detailsQing();
  //     },
  //     fail: function(res) {
  //       utils.showError(res.message)
  //     },
  //     complete: function() {
  //       setTimeout(function() {
  //         wx.hideLoading();
  //         wx.stopPullDownRefresh();
  //       }, 500)
  //     }
  //   });
  // },
  demoHeight: function() {
    var that = this;
    //创建节点选择器
    var query = wx.createSelectorQuery();
    //选择id

    query.select('#wizhiDemo').boundingClientRect()
    query.exec(function(res) {
      if (res[0].height) {
        // console.log('打印demo的元素的信息', res);
        console.log('打印高度', res[0].height);
        if (res[0].height > 320) {
          that.setData({
            scrollTop: res[0].height
          })
        }
      }
    })
  },
  // 请求房间详情
  detailsQing: function() {
    var that = this;
    utils.showLoading();
    qcloud.request({
      login: true,
      url: config.service.liveDetailsUrl,
      data: {
        id: that.data.ia
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        if (res.data.data.info != '' && res.data.data.info != null && res.data.data.info != undefined) {
          var article = res.data.data.info.content;
          WxParse.wxParse('article', 'html', article, that, 5);
          if (res.data.data.info.userId == that.data.userId) {
            that.setData({
              beginHide: true
            })
          }
          that.setData({
            detailData: res.data.data,
            guanzhuShow: res.data.data.isLiveColl,
            countNum: commons.dateTools.wanNumZh(res.data.data.info.click)
          })
          wx.downloadFile({
            url: res.data.data.info.thumb,
            success(res) {
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                bgImg = res.tempFilePath;
              }
            }
          })
          // 获取直播倒计时
          that.show_time(res.data.data.info.stime * 1000);
          // 设置标题
          wx.setNavigationBarTitle({
            title: res.data.data.info.title
          });
          that.clickzan();
        } else {
          utils.showError("改视频已删除")
          setTimeout(function() {
            wx.switchTab({
              url: '../index/index',
            })
          }, 1500)
        }
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {

      }
    });
  },
  // 倒计时
  show_time: function(time_endS) {
    var that = this;
    setTimeout(function() {
      that.setData({
        timeShow: true
      })
    }, 1000)
    var time_end = time_endS;
    var int_day, int_hour, int_minute, int_second;
    var timerID = setInterval(function() {
      // 获取当前时间
      var time_now = new Date().getTime();
      // 结束时间减去当前时间
      var time_distance = time_end - time_now;
      if (time_distance >= 0) {
        // 天时分秒换算
        int_day = Math.floor(time_distance / 86400000)
        time_distance -= int_day * 86400000;
        int_hour = Math.floor(time_distance / 3600000)
        time_distance -= int_hour * 3600000;
        int_minute = Math.floor(time_distance / 60000)
        time_distance -= int_minute * 60000;
        int_second = Math.floor(time_distance / 1000)
        // 天时分秒为单数时、前面加零站位
        if (int_day < 10)
          int_day = "0" + int_day;
        if (int_hour < 10)
          int_hour = "0" + int_hour;
        if (int_minute < 10)
          int_minute = "0" + int_minute;
        if (int_second < 10)
          int_second = "0" + int_second;

        // 显示时间
        var timeHtml = "距开始还有:" + int_day + "天" + int_hour + "小时" + int_minute + "分" + int_second + "秒";
        that.setData({
          dataTimeHtml: timeHtml
        })
      } else {
        that.setData({
          timeShow: false,
          dataTimeHtml: "距开始还有:00天00小时00分00秒"
        })
        clearInterval(timerID)
      }
    }, 1000);
  },
  websoket: function() {
    var _this = this;
    //建立连接
    const socket = wx.connectSocket({
      url: "wss://live.xiaochengshi.net/wss",
      method: 'GET',
      success: function() {
        console.log("连接成功...")
      },
      fail: function() {
        console.log("连接失败...")
      }
    })
    // 判断是否断开连接
    wx.onSocketError(function(res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    // 当socket连接打开时，输入用户名id登录
    // 建立连接
    wx.onSocketOpen((res) => {
      var login_data = {
        "type": "login",
        "client_name": this.data.nickname,
        "userId": this.data.liaoTianid,
        "room_id": this.data.ia,
        "avatar_url": this.data.avatar_url
      }
      console.log("websocket握手成功，发送登录数据:", login_data);
      socket.send({
        data: JSON.stringify(login_data)
      })

    })
    // 监听WebSocket 接受到服务器的消息事件
    wx.onSocketMessage((res) => {
      var that = this;
      var _data = JSON.parse(res.data);
      if (_data.type == 'ping') {
        wx.sendSocketMessage({
          type: 'ping'
        })
      } else if (_data.type == 'say') {
        var list = [];
        list = this.data.newsList;
        list.push(_data);
        this.setData({
          newsList: list
        });
        if (that.data.isOpenData == 0) {
          that.demoHeight();
        }
      } else if (_data.type == 'save') {
        var temp = {
          id: that.data.ia,
          userId: that.data.liaoTianid,
          client_name: that.data.nickname,
          avatar_url: that.data.avatar_url,
          content: that.data.input
        }
        qcloud.request({
          login: false,
          url: 'https://live.xiaochengshi.net/Api/Article/chitchat.html',
          data: temp,
          success: function() {
            that.setData({
              input: ''
            })
          },
          fail: function() {}
        })
      }
    })
  },
  // 发送聊天
  sendFasong: function() {
    var that = this;
    var timed = that.data.detailData.info.times * 1000;
    if (this.data.input !== '') {
      if (tsay == 0) {
        tsay = 1;
        var timeNum = setTimeout(function() {
          tsay = 0;
          clearTimeout(timeNum);
        }, timed);
        var temp = {
          type: 'say',
          userId: that.data.liaoTianid,
          to_client_id: 'all',
          to_client_name: that.data.nickname,
          avatar_url: that.data.avatar_url,
          content: that.data.input
        }
        wx.sendSocketMessage({
          data: JSON.stringify(temp)
        })
      } else {
        utils.showError("您说话太快了");
      }
    } else {
      utils.showError("请输入发言");
    }
  },
  // 检测滚动条
  scroll: function(e) {
    console.log(e.detail.scrollHeight)
    this.setData({
      scrollTop: e.detail.scrollHeight
    })
  },
  // 获取内容
  bindChange: function(res) {
    this.setData({
      input: res.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      currentTab: 0
    })
    this.ctx = wx.createLivePlayerContext('player')
    // 获取网页的地址
    this.isopen();
  },
  isopen() {
    var that = this;
    var wxH = wx.getSystemInfoSync().windowHeight;
    qcloud.request({
      login: true,
      url: config.service.isOpenUrl,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        // 开关
        that.setData({
          isOpenData: res.data.data.fieldValue
        })
      },
      fail: function(res) {
        utils.showError('请求出错')
      },
      complete: function() {
        setTimeout(function() {
          if (Session.get().userInfo) {
            that.setData({
              wxHeight: wxH - 315,
              detailID: that.data.ia,
              access_token: Session.get().userInfo.access_token,
              nickname: Session.get().userInfo.nickname,
              avatar_url: Session.get().userInfo.avatar_url,
              liaoTianid: Session.get().userInfo.id,
              userId: Session.get().userInfo.id,
            })
            // 记录历史记录
            that.indexListData();
            // 请求历史聊天信息
            that.roomcommonUrl();
            // 请求视频详情
            that.detailsQing();
            // 请求视频的详情
            that.detailsQing();
            // 发起聊天请求
            that.websoket();
            wx.downloadFile({
              url: Session.get().userInfo.avatar_url,
              success(res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                  headerImg = res.tempFilePath;
                }
              }
            })
          } else {
            // 如果获取不到userInfo的信息 从头走三次
            if (JlnumS < 3) {
              // 如果没有获取用户信息回调授权接口
              that.isopen()
            } else {
              utils.showError("请检查您的网络")
            }
            JlnumS = JlnumS + 1;
          }
          console.log("JlnumS:" + JlnumS)
        }, 1000)
      }
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    wx.closeSocket()
    console.log('退出房间1')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.closeSocket()
    console.log('退出房间2');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this;
    this.lives();
    return {
      title: this.data.detailData.info.title,
      path: '/pages/details/details?ia=' + this.data.detailData.info.id,
      imageUrl: this.data.detailData.info.thumb,
      success: function() {
        utils.showSuccess("转发成功");
      }

    };
  },
  lives: function() {
    qcloud.request({
      login: false,
      url: config.service.livesUrl,
      data: {
        room_id: this.data.ia
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log("分享统计+1")
      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {

      }
    });
  }
};
var data = Object.assign(index.data, register.data);
var page = Object.assign(index, register);
page.data = data;
Page(page);